
// #ifdef H5
import weixin from 'weixin-jsapi';
// #endif
// import API_USER from '@/api/user';
import { useUserStore } from "@/store/modules/user";
const baseURL = import.meta.env.VITE_APP_API_HOST || 'https://api.example.com';



// 复制
export const copyText = (text: string) => {
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'none',
        duration: 2000
      })
    },
  })
}

export const toast = (msg: string) => {
  uni.showToast({
    title: msg,
    icon: 'none',
    duration: 2000
  })
}


// 选择图片
export const selectImg = () => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
 * 获取链接全部参数
 * @description 兼容search，hash并存情况
 * @param {string} [url]  链接
 * @returns {Record<string, string>} 返回包含当前URL参数的对象
 * @example
 * ```js
 * getURLParameters();
 *
 * getURLParameters('http://www.baidu.com?name=1&age=2#/demoPage?weight=3&o=4');
 * // => {name: "1", age: "2", weight: "3", o: "4"}
 * ```
 */
export function getURLParameters(url: string): Record<string, string> {
  const reg = /([^?=&]+)(=([^&#]*))/g;
  const href = url || window.location.href;
  const matchList = href.match(reg) || [];
  const obj = {};

  matchList.forEach((v) => {
    obj[v.slice(0, v.indexOf('='))] = decodeURIComponent(v.slice(v.indexOf('=') + 1));
  });

  return obj;
}


/**
 * 获取链接某个参数
 * @description 兼容search，hash并存情况
 * @param {string} key 参数名称
 * @param {string} [url]  链接
 * @returns {string} 返回参数值
 * @example
 * ```js
 * getQueryString('name'); // null
 * getQueryString('name', 'http://www.baidu.com?name=1&age=2'); // 1
 * ```
 */
export function getQueryString(key: string, url: string) {
  const reg = new RegExp(`([?&]+)${key}=([^&#]*)`);
  const href = url || window.location.href;
  const results = href.substring(1).match(reg);

  if (!results) return null;
  if (!results[2]) return '';

  return decodeURIComponent(results[2]);
}


// 微信 sdk 配置函数
export async function wechatSdkConfig(option: any): Promise<void> {
  try {
    // 假设 apiJsConfig 是一个异步函数，需要提前定义
    const userStore = useUserStore();
    const res:any = userStore.config.scan.info
    console.log(res)
    // 调用微信 JS-SDK 的 config 方法进行配置
    weixin.config({
      debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来，若要查看传入的参数，可以在 pc 端打开，参数信息会通过 log 打出，仅在 pc 端时才会打印。
      appId: res.appId, // 必填，公众号的唯一标识
      timestamp: res.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.nonceStr, // 必填，生成签名的随机串
      signature: res.signature, // 必填，签名
      jsApiList: res.jsApiList // 必填，需要使用的 JS 接口列表
    });

    // 配置成功，可添加额外逻辑
    console.log('微信 JS-SDK 配置成功');
    share(option)
  } catch (error) {
    // 捕获并处理错误
    console.error('微信 JS-SDK 配置失败:', error);
    throw error;
  }
}

// 定义分享选项的类型
interface ShareOption {
  shareTitle: string;
  shareLink: string;
  shareImage: string;
  shareDesc: string;
}

// 定义分享成功回调函数的类型
type ShareSuccessCallback = (res: any) => void;

// 封装通用的分享配置函数
const configureShare = (
  configFunction: (options: any) => void,
  option: ShareOption,
  successCallback: ShareSuccessCallback
) => {
  configFunction({
    title: option.shareTitle,
    link: option.shareLink,
    imgUrl: option.shareImage,
    desc: option.shareDesc,
    success: successCallback,
    cancel: () => {
      console.log('用户取消分享');
    }
  });
};

// 微信分享
export const share = (option: ShareOption) => {
  console.log(option)
  weixin.ready(() => {
    const successCallback: ShareSuccessCallback = (res) => {
      console.log('分享设置成功', res);
    };

    // 发送给好友（旧）
    configureShare(weixin.onMenuShareAppMessage, option, successCallback);

    // 分享到朋友圈（旧）
    configureShare(weixin.onMenuShareTimeline, option, successCallback);

    // 分享到朋友圈（新）
    if ('updateTimelineShareData' in weixin) {
      configureShare(weixin.updateTimelineShareData, { ...option, desc: '' }, successCallback);
    }

    // 发送给好友（新）
    if ('updateAppMessageShareData' in weixin) {
      configureShare(weixin.updateAppMessageShareData, option, successCallback);
    }

  
  });
};

// 微信登陆
export const wxH5Login = async (appid:string) => {
  const urls = window.location.href;
  const params = getCache('redirectUrl')?.split('?')[1]
  const redirectUrl = urls?.split('#')[0] + '#/?' + params;
  const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=` + appid+ `&redirect_uri=` + encodeURIComponent(redirectUrl) + `&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
  window.location.replace(url)
}

// 存缓存
export const setCache = (key: string, value: any) => {
  uni.setStorageSync(key, value);
}

// 取缓存
export const getCache = (key: string) => {
  return uni.getStorageSync(key);
}

// 移除缓存
export const removeCache = (key: string) => {
  uni.removeStorageSync(key);
}

// 11位时间戳转时间
export const timestampToTime = (timestamp: number) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  const monthStr = month < 10 ? `0${month}` : month;
  const dayStr = day < 10 ? `0${day}` : day;
  const hourStr = hour < 10 ? `0${hour}` : hour;
  const minuteStr = minute < 10 ? `0${minute}` : minute;
  const secondStr = second < 10 ? `0${second}` : second;
  return `${year}-${monthStr}-${dayStr} ${hourStr}:${minuteStr}:${secondStr}`;
}

// 路由跳转
export const goUrl = (url: string,isLogin:boolean) => {
  if(isLogin){
    const userStore = useUserStore();
    if(!userStore.token){
      // #ifdef H5
      const href = window.location.href;
      setCache('redirectUrl', href);
      // #endif
      uni.navigateTo({
        url: '/pages/login/index'
      })
      return
    }
    uni.navigateTo({
      url: url
    })
    return
  }else{
    uni.navigateTo({
      url: url
    })
  }

}


export function uploadFile(path: any) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseURL + 'api.data/upload',
      filePath: path,
      name:"file" ,
      success: (res) => {
        try {
          let data = JSON.parse(res.data);
          if (data.code == 1) {
            resolve(data.data);
          } else {
            reject();
          }
        } catch (e) {
          reject();
        }
      },
      fail: (err) => {
        reject();
      },
    });
  });
}

// 秒转成时分秒
export function secondsToTime(time: number) {
  const hours = Math.floor(time / 3600);
  const minutes = Math.floor((time % 3600) / 60);
  const seconds = time % 60;
  return `${minutes}分${seconds}秒`;
}


// 确认弹框
export function confirmDialog(title: string, content: string) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: title,
      content: content,
      success: (res) => {
        if (res.confirm) {
          resolve(true);
        } else if (res.cancel) {
          reject(false);
        }
      },
    });
  });
}


// 时间戳转日期
export function timestampToDate(timestamp: number, format = '-') {

  if (!timestamp) {
    return '';
  }
  
  const date = new Date(timestamp *1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0'); 
  const dataTime = `${year}${format}${month}${format}${day} ${hours}:${minutes}:${seconds}` 
  return dataTime;
}

